import React, { useState, useEffect } from "react";
import { Card, Table, Select, Button, message } from "antd";
import { Bar } from "react-chartjs-2";
import { Chart as ChartJS, BarElement, CategoryScale, LinearScale, Tooltip, Legend } from "chart.js";
import axios from "axios";
import dayjs from "dayjs";

ChartJS.register(BarElement, CategoryScale, LinearScale, Tooltip, Legend);

const UserProfile = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [selectedUser, setSelectedUser] = useState(null);
  const [behaviorData, setBehaviorData] = useState([]);
  const fetchUsers = async () => {
    setLoading(true);
    try {
      const response = await axios.get("http://localhost:5000/api/users");
      setUsers(response.data);
    } catch (error) {
      console.error("Error fetching users:", error);
      message.error("获取用户列表失败");
    } finally {
      setLoading(false);
    }
  };

  const fetchBehaviorData = async (username) => {
    try {
      const response = await axios.get("http://localhost:5000/api/user/behavior", {
        params: { username },
      });
      setBehaviorData(response.data);
    } catch (error) {
      console.error("Error fetching behavior data:", error);
      message.error("获取用户行为数据失败");
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  const handleSelectUser = (username) => {
    setSelectedUser(username);
    fetchBehaviorData(username);
  };

  const handlePushNotification = async () => {
    try {
      await axios.post("http://localhost:5000/api/notify", {
        type: "个性化推送",
        username: selectedUser,
        message: "为您推荐专属优惠：测算服务 8 折！",
      });
      message.success("推送成功");
    } catch (error) {
      console.error("Error pushing notification:", error);
      message.error("推送失败");
    }
  };

  const columns = [
    { title: "用户名", dataIndex: "username", key: "username" },
    { title: "测算次数", dataIndex: "fortune_count", key: "fortune_count" },
    { title: "测算偏好", dataIndex: "fortune_types", key: "fortune_types" },
    { title: "最近活跃", dataIndex: "last_fortune_time", key: "last_fortune_time", render: (text) => dayjs(text).format("YYYY-MM-DD HH:mm:ss") },
  ];

  const behaviorChartData = {
    labels: behaviorData.map((item) => item.event),
    datasets: [
      {
        label: "行为次数",
        data: behaviorData.map((item) => item.count),
        backgroundColor: "#36A2EB",
      },
    ],
  };

  return (
    <div style={{ padding: "24px" }}>
      <div style={{ marginBottom: "24px" }}>
        <Select
          style={{ width: 200 }}
          placeholder="选择用户"
          onChange={handleSelectUser}
        >
          {users.map((user) => (
            <Select.Option key={user.username} value={user.username}>
              {user.username}
            </Select.Option>
          ))}
        </Select>
        {selectedUser && (
          <Button type="primary" onClick={handlePushNotification} style={{ marginLeft: 16 }}>
            推送个性化优惠
          </Button>
        )}
      </div>
      <Table
        columns={columns}
        dataSource={users}
        rowKey="username"
        loading={loading}
        pagination={{ pageSize: 10 }}
      />
      {selectedUser && behaviorData.length > 0 && (
        <Card title={`${selectedUser} 的行为分析`} style={{ marginTop: 24 }}>
          <Bar data={behaviorChartData} options={{ maintainAspectRatio: false }} height={250} />
        </Card>
      )}
    </div>
  );
};

export default UserProfile;